package com.bgdCA.config;

import com.bgdCA.domain.SysLog;
import com.bgdCA.service.ISysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Arrays;
import java.util.Date;

/**
 * @author Promise
 * @createTime 2018年12月18日 下午9:33:28
 * @description 切面日志配置
 */
@Aspect
@Component
public class LogAsPect {

    private final static Logger log = org.slf4j.LoggerFactory.getLogger(LogAsPect.class);
    @Autowired
    private ISysLogService sysLogService;


    @Pointcut("execution(public * com.bgdCA.controller..*.*(..))")

    public void pointcutController() {
    }

    @Before("pointcutController()")
    public void around2(JoinPoint point) {
        long beginTime = System.currentTimeMillis();
        //获取目标方法
        String methodNam = point.getSignature().getDeclaringTypeName() + "." + point.getSignature().getName();

        //获取方法参数
        String params = Arrays.toString(point.getArgs());

        long endTime = System.currentTimeMillis();

        insertLog(point, endTime - beginTime);

        log.info("get in {} params :{}", methodNam, params);
    }


    private void insertLog(JoinPoint point, long time) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        SysLog sys_log = new SysLog();

        Log userAction = method.getAnnotation(Log.class);
        if (userAction != null) {
            // 注解上的描述
            sys_log.setUser_action(userAction.value());
        }

        // 请求的类名
        String className = point.getTarget().getClass().getName();
        // 请求的方法名
        String methodName = signature.getName();
        // 请求的方法参数值
        String args = Arrays.toString(point.getArgs());

        //从session中获取当前登陆人id
// Long useride = (Long)SecurityUtils.getSubject().getSession().getAttribute("userid");

        long userid = 1L;//应该从session中获取当前登录人的id，这里简单模拟下

        sys_log.setUser_action(className + "/" + methodName);

        sys_log.setUser_id(userid);

        sys_log.setCreate_time(new Timestamp(new Date().getTime()));

        sys_log.setParams(args);

        log.info("当前登陆人：{},类名:{},方法名:{},参数：{},执行时间：{}", userid, className, methodName, args, time);
        sysLogService.insertLog(sys_log);
    }
}